package com.example.myrecyclerview;

import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

import com.example.myrecyclerview.bean.Book;

import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;

public class DataManager {
    private ArrayList<Book> books;
    private String fileName = "bookData";
    private File sdCardDir;

    public DataManager(){
        if(!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
            Toast.makeText(MainActivity.getContext(),"手机没有SD卡！",Toast.LENGTH_SHORT).show();
        }
        sdCardDir = Environment.getExternalStorageDirectory();//获取SDCard目录
        books = new ArrayList<Book>();
    }
    public void writeBookByStream(ArrayList<Book> books){
        try{
            File saveFile = new File(sdCardDir,fileName);
            FileOutputStream fout = new FileOutputStream(saveFile);
            ObjectOutputStream Oout = new ObjectOutputStream(fout);
            for(Book book:books) {
                Oout.writeObject(book);
            }
            Oout.close();
            fout.close();
        }catch (Exception e){
            Log.d("<Test>",e.toString());
        }
    }

    public ArrayList<Book> readBookByStream() throws IOException {
        books.clear();
        FileInputStream fin = null;
        ObjectInputStream oin = null;
        try {
            File saveFile = new File(sdCardDir,fileName);
            fin = new FileInputStream(saveFile);
            oin = new ObjectInputStream(fin);
            while(true) {
                books.add((Book)oin.readObject());
            }
        }catch(EOFException e) {
            Log.d("<Test>","已读到文件末尾");
        }catch (Exception e) {

        }finally {
            oin.close();
            fin.close();
        }
        return books;
    }
}
